const socketIO = require('socket.io');
const jwt = require('jsonwebtoken');
const config = require('../config');
const whatsappService = require('./whatsappService');
const { User } = require('../models');
const { socketAuth } = require('../middlewares/authMiddleware');
const logger = require('../utils/logger');

let io;

/**
 * 初始化Socket.IO服务
 */
const setup = (server) => {
  io = socketIO(server, {
    cors: {
      origin: process.env.CORS_ORIGIN || '*',
      methods: ['GET', 'POST'],
      credentials: true
    },
    pingTimeout: 60000, // 增加ping超时时间
    pingInterval: 25000, // 增加ping间隔
    connectTimeout: 30000, // 连接超时
    maxHttpBufferSize: 5e6, // 5MB
    transports: ['websocket', 'polling']
  });

  // 添加认证中间件
  io.use(socketAuth);

  io.on('connection', (socket) => {
    const userId = socket.user?.id;

    logger.info(`Socket连接: ${socket.id} - 用户ID: ${userId}`);

    // 将用户加入对应的房间
    if (userId) {
      socket.join(`user:${userId}`);
      logger.debug(`用户 ${userId} 加入房间 user:${userId}`);
    }

    // 添加心跳机制
    const heartbeatInterval = setInterval(() => {
      socket.emit('heartbeat');
    }, 30000);

    // 监听心跳响应
    socket.on('heartbeat-response', () => {
      logger.debug(`收到心跳响应: ${socket.id}`);
    });

    // 监听认证事件
    socket.on('auth', (data) => {
      logger.info(`Socket ${socket.id} 认证成功`);
      socket.emit('auth_success', { userId: socket.user?.id });
    });

    // 错误处理
    socket.on('error', (error) => {
      logger.error(`Socket错误 ${socket.id}:`, error);
    });

    // 断开连接处理
    socket.on('disconnect', (reason) => {
      logger.info(`Socket断开连接 ${socket.id}, 原因: ${reason}`);
      clearInterval(heartbeatInterval);
    });

    // WhatsApp二维码扫描请求
    socket.on('whatsapp:requestQR', () => {
      whatsappService.generateQR(socket.user.id)
        .then(qrData => {
          socket.emit('whatsapp:qr', qrData);
        })
        .catch(error => {
          socket.emit('whatsapp:error', {
            message: '生成二维码失败',
            error: error.message
          });
        });
    });
    
    // WhatsApp连接状态请求
    socket.on('whatsapp:connectionStatus', () => {
      sendConnectionStatus(socket);
    });
    
    // WhatsApp断开连接请求
    socket.on('whatsapp:disconnect', () => {
      whatsappService.disconnectClient(socket.user.id)
        .then(() => {
          socket.emit('whatsapp:disconnected', { message: 'WhatsApp已断开连接' });
        })
        .catch(error => {
          socket.emit('whatsapp:error', {
            message: '断开连接失败',
            error: error.message
          });
        });
    });
    
    // 监听联系人状态请求
    socket.on('whatsapp:checkContactStatus', (contactId) => {
      whatsappService.getContactById(contactId, socket.user.id)
        .then(contact => {
          if (contact) {
            socket.emit('whatsapp:contactStatus', {
              contact,
              timestamp: new Date()
            });
          }
        })
        .catch(error => {
          socket.emit('whatsapp:error', {
            message: '获取联系人状态失败',
            error: error.message
          });
        });
    });
    
    // 监听联系人在线状态订阅请求
    socket.on('whatsapp:subscribeContactStatus', (contactId) => {
      whatsappService.subscribeContactStatus(contactId, socket.user.id)
        .then(() => {
          socket.emit('whatsapp:subscribed', {
            message: '已订阅联系人状态更新',
            contactId
          });
        })
        .catch(error => {
          socket.emit('whatsapp:error', {
            message: '订阅联系人状态失败',
            error: error.message
          });
        });
    });
    
    // 监听敏感内容事件处理设置
    socket.on('settings:sensitiveContent', (enabled) => {
      // 保存用户的敏感内容通知设置
      socket.sensitiveContentNotify = enabled;
      
      socket.emit('settings:updated', {
        setting: 'sensitiveContentNotify',
        value: enabled
      });
    });
  });

  // 全局错误处理
  io.engine.on('connection_error', (err) => {
    logger.error('Socket.IO连接错误:', err);
  });

  logger.info('Socket.IO服务已初始化');

  // 设置WhatsApp服务回调
  setupWhatsAppCallbacks();

  return io;
};

/**
 * 发送WebSocket通知到特定用户
 */
const emitToUser = (userId, event, data) => {
  if (io) {
    io.to(`user:${userId}`).emit(event, data);
    logger.debug(`发送事件 ${event} 到用户 ${userId}`);
    return true;
  }
  
  logger.warn('Socket.IO尚未初始化，无法发送消息');
  return false;
};

/**
 * 发送WebSocket通知给所有管理员
 */
const emitToAdmins = (event, data) => {
  if (io) {
    io.to('role:admin').emit(event, data);
    logger.debug(`发送事件 ${event} 到所有管理员`);
    return true;
  }
  
  logger.warn('Socket.IO尚未初始化，无法发送消息');
  return false;
};

/**
 * 发送WebSocket通知给所有用户
 */
const emitToAll = (event, data) => {
  if (io) {
    io.emit(event, data);
    logger.debug(`广播事件 ${event} 到所有用户`);
    return true;
  }
  
  logger.warn('Socket.IO尚未初始化，无法发送消息');
  return false;
};

/**
 * 发送当前连接状态
 */
const sendConnectionStatus = async (socket) => {
  try {
    const status = await whatsappService.getConnectionStatus(socket.user.id);
    socket.emit('whatsapp:connectionStatus', status);
  } catch (error) {
    socket.emit('whatsapp:error', {
      message: '获取连接状态失败',
      error: error.message
    });
  }
};

/**
 * 设置WhatsApp服务回调函数
 */
const setupWhatsAppCallbacks = () => {
  // QR码更新回调 - 支持用户专属事件
  whatsappService.onQRCodeUpdate((userId, qrData) => {
    emitToUser(userId, `whatsapp:qr:${userId}`, {
      ...qrData,
      userId
    });
    
    // 同时发送通用事件以保持兼容性
    emitToUser(userId, 'whatsapp:qr', qrData);
  });
  
  // 客户端准备就绪回调 - 支持用户专属事件
  whatsappService.onClientReady((userId) => {
    const readyData = {
      message: 'WhatsApp客户端已准备就绪',
      timestamp: new Date(),
      userId
    };
    
    emitToUser(userId, `whatsapp:ready:${userId}`, readyData);
    emitToUser(userId, 'whatsapp:ready', readyData);
    
    // 发送状态更新
    emitToUser(userId, `whatsapp:status:${userId}`, {
      status: 'connected',
      message: 'WhatsApp已成功连接',
      userId,
      timestamp: new Date()
    });
    
    // 通知管理员
    emitToAdmins('admin:user_status_change', {
      userId,
      status: 'connected',
      message: `用户ID ${userId} 的WhatsApp客户端已连接`,
      type: 'success',
      timestamp: new Date()
    });
  });
  
  // 客户端认证失败回调 - 支持用户专属事件
  whatsappService.onAuthFailure((userId, error) => {
    const failureData = {
      message: 'WhatsApp认证失败',
      error: error.message,
      timestamp: new Date(),
      userId
    };
    
    emitToUser(userId, `whatsapp:authFailure:${userId}`, failureData);
    emitToUser(userId, 'whatsapp:authFailure', failureData);
    
    // 发送状态更新
    emitToUser(userId, `whatsapp:status:${userId}`, {
      status: 'error',
      message: '认证失败',
      userId,
      timestamp: new Date()
    });
  });
  
  // 客户端断开连接回调 - 支持用户专属事件
  whatsappService.onDisconnected((userId, reason) => {
    const disconnectData = {
      message: 'WhatsApp已断开连接',
      reason,
      timestamp: new Date(),
      userId
    };
    
    emitToUser(userId, `whatsapp:disconnected:${userId}`, disconnectData);
    emitToUser(userId, 'whatsapp:disconnected', disconnectData);
    
    // 发送状态更新
    emitToUser(userId, `whatsapp:status:${userId}`, {
      status: 'disconnected',
      message: '连接已断开',
      userId,
      timestamp: new Date()
    });
    
    // 通知管理员
    emitToAdmins('admin:user_status_change', {
      userId,
      status: 'disconnected',
      message: `用户ID ${userId} 的WhatsApp客户端已断开连接`,
      type: 'warning',
      timestamp: new Date()
    });
  });
  
  // 新消息回调 - 支持用户专属事件
  whatsappService.onMessage((userId, message) => {
    // 检查消息是否包含敏感内容
    const filterService = require('./filterService');
    const detectionResult = filterService.detectSensitiveContent(message.body);
    
    // 如果包含敏感内容，添加标记
    if (detectionResult.hasSensitiveContent) {
      message.hasSensitiveContent = true;
      message.sensitiveType = detectionResult.numberDetection.type || 'keyword';
      
      // 如果设置了保存原始内容，则保存
      if (filterService.getSettings().storeOriginalContent) {
        message.originalContent = message.body;
      }
      
      // 过滤内容
      message.body = filterService.filterSensitiveContent(message.body).filteredText;
      
      // 通知管理员有敏感内容
      if (filterService.getSettings().notifyAdminOnDetection) {
        emitToAdmins('sensitive:content', {
          messageId: message.id.id,
          userId,
          contact: {
            id: message.from,
            name: message.sender || '未知'
          },
          contentType: detectionResult.numberDetection.type || 'keyword',
          timestamp: new Date()
        });
      }
    }
    
    const messageData = {
      ...message,
      userId
    };
    
    emitToUser(userId, `whatsapp:message:${userId}`, messageData);
    emitToUser(userId, 'whatsapp:message', message);
  });
  
  // 消息状态变化回调 - 支持用户专属事件
  whatsappService.onMessageStatusChange((userId, messageId, status) => {
    const statusData = {
      messageId,
      status,
      timestamp: new Date(),
      statusDescription: getMessageStatusDescription(status),
      userId
    };
    
    emitToUser(userId, `whatsapp:messageStatus:${userId}`, statusData);
    emitToUser(userId, 'whatsapp:messageStatus', statusData);
  });
  
  // 联系人状态变化回调 - 支持用户专属事件
  whatsappService.onContactStatusChange((userId, contact) => {
    const contactInfo = {
      id: contact.id.user,
      name: contact.name || contact.pushname || '未知联系人',
      status: contact.status || 'unknown',
      lastSeen: contact.lastSeen || null,
      profilePic: contact.profilePicUrl,
      isGroup: contact.isGroup || false,
      timestamp: new Date(),
      userId
    };
    
    emitToUser(userId, `whatsapp:contactStatus:${userId}`, {
      contact: contactInfo,
      timestamp: new Date()
    });
    
    emitToUser(userId, 'whatsapp:contactStatus', {
      contact: contactInfo,
      timestamp: new Date()
    });
    
    // 发送详细状态更新
    if (contact.status) {
      const statusDescription = getContactStatusDescription(contact.status);
      
      emitToUser(userId, `whatsapp:contactStatusDetails:${userId}`, {
        contact: contactInfo,
        statusDescription,
        timestamp: new Date()
      });
      
      // 如果联系人变为在线，发送特别通知
      if (contact.status === 'online') {
        emitToUser(userId, 'notification', {
          title: '联系人状态变化',
          message: `${contactInfo.name} 已上线`,
          type: 'info',
          timestamp: new Date()
        });
      } else if (contact.status === 'offline' && contact.lastSeen) {
        // 联系人下线通知
        emitToUser(userId, 'notification', {
          title: '联系人状态变化',
          message: `${contactInfo.name} 已离线`,
          type: 'info',
          timestamp: new Date()
        });
      }
    }
  });
  
  // 电池状态变化回调 - 支持用户专属事件
  whatsappService.onBatteryStatus((userId, batteryInfo) => {
    const batteryData = {
      ...batteryInfo,
      timestamp: new Date(),
      userId
    };
    
    emitToUser(userId, `whatsapp:batteryStatus:${userId}`, batteryData);
    emitToUser(userId, 'whatsapp:batteryStatus', batteryData);
    
    // 当电池电量较低时发送警告
    if (batteryInfo.percentage < 20 && !batteryInfo.plugged) {
      emitToUser(userId, 'notification', {
        title: '设备电池状态',
        message: `您的WhatsApp设备电量低于20%，请及时充电`,
        type: 'warning',
        timestamp: new Date()
      });
    }
  });
  
  // 连接状态变化详细通知 - 支持用户专属事件
  whatsappService.onConnectionStateChange((userId, state) => {
    const stateMessages = {
      'CONNECTED': '您已成功连接到WhatsApp',
      'CONNECTING': '正在连接到WhatsApp...',
      'DISCONNECTED': '与WhatsApp的连接已断开',
      'SYNCING': '正在同步WhatsApp数据...',
      'CONFLICT': '在其他设备上检测到WhatsApp会话',
      'TIMEOUT': '连接超时，请重试',
      'OPENING': '正在打开WhatsApp会话...',
      'PAIRING': '正在配对设备...',
      'UNLAUNCHED': 'WhatsApp未启动'
    };
    
    const stateDetails = {
      'CONNECTED': {
        description: '您的WhatsApp账号已成功连接到系统，可以开始收发消息。',
        advice: '保持页面开启以保持连接状态。',
        color: 'success'
      },
      'CONNECTING': {
        description: '正在尝试连接到WhatsApp服务器...',
        advice: '请稍候，连接过程可能需要几秒钟。',
        color: 'processing'
      },
      'DISCONNECTED': {
        description: '您的WhatsApp连接已断开。',
        advice: '请检查您的网络连接，或重新扫描二维码。',
        color: 'error'
      },
      'SYNCING': {
        description: '正在与WhatsApp服务器同步数据。',
        advice: '请稍候，同步过程可能需要一些时间。',
        color: 'processing'
      },
      'CONFLICT': {
        description: '检测到您的WhatsApp账号在其他设备上登录。',
        advice: '请关闭其他设备上的WhatsApp，或重新扫描二维码。',
        color: 'warning'
      },
      'TIMEOUT': {
        description: '连接WhatsApp服务器超时。',
        advice: '请检查您的网络连接，然后重试。',
        color: 'error'
      },
      'OPENING': {
        description: '正在打开WhatsApp会话...',
        advice: '请稍候，会话即将准备就绪。',
        color: 'processing'
      },
      'PAIRING': {
        description: '正在配对您的设备...',
        advice: '请在手机上确认配对请求。',
        color: 'processing'
      },
      'UNLAUNCHED': {
        description: 'WhatsApp尚未启动。',
        advice: '请扫描二维码以启动WhatsApp。',
        color: 'default'
      }
    };
    
    const connectionData = {
      state,
      message: stateMessages[state] || `连接状态: ${state}`,
      details: stateDetails[state] || {
        description: `连接状态: ${state}`,
        advice: '请保持页面开启。',
        color: 'default'
      },
      timestamp: new Date(),
      userId
    };
    
    // 发送用户专属的状态更新
    emitToUser(userId, `whatsapp:connection_state:${userId}`, connectionData);
    emitToUser(userId, 'whatsapp:connectionState', connectionData);
    
    // 对重要状态变化发送通知
    if (['CONNECTED', 'DISCONNECTED', 'CONFLICT', 'TIMEOUT'].includes(state)) {
      emitToUser(userId, 'notification', {
        title: 'WhatsApp连接状态',
        message: stateMessages[state] || `连接状态: ${state}`,
        type: state === 'CONNECTED' ? 'success' : 'warning',
        timestamp: new Date()
      });
    }
    
    // 通知管理员重要的状态变化
    if (['DISCONNECTED', 'CONFLICT', 'TIMEOUT'].includes(state)) {
      emitToAdmins('admin:user_status_change', {
        userId,
        state,
        message: `用户ID ${userId} 的WhatsApp ${stateMessages[state].toLowerCase()}`,
        type: 'warning',
        timestamp: new Date()
      });
    }
  });
};

/**
 * 获取消息状态描述
 * @param {string} status 消息状态代码
 * @returns {object} 状态描述对象
 */
const getMessageStatusDescription = (status) => {
  const statusMap = {
    'ERROR': { text: '发送失败', color: 'error' },
    'PENDING': { text: '等待发送', color: 'warning' },
    'SERVER_ACK': { text: '服务器已接收', color: 'processing' },
    'DELIVERY_ACK': { text: '已送达', color: 'processing' },
    'READ': { text: '已读', color: 'success' },
    'PLAYED': { text: '已播放', color: 'success' }
  };
  
  return statusMap[status] || { text: status, color: 'default' };
};

/**
 * 获取联系人状态描述
 * @param {string} status 联系人状态
 * @returns {object} 状态描述对象
 */
const getContactStatusDescription = (status) => {
  const statusMap = {
    'online': { text: '在线', color: 'success' },
    'offline': { text: '离线', color: 'default' },
    'typing': { text: '正在输入...', color: 'processing' },
    'recording': { text: '正在录音...', color: 'processing' },
    'unavailable': { text: '不可用', color: 'error' }
  };
  
  return statusMap[status] || { text: status, color: 'default' };
};

// 发送事件到指定房间
const emitToRoom = (room, event, data) => {
  if (io) {
    io.to(room).emit(event, data);
    logger.debug(`发送事件 ${event} 到房间 ${room}`);
    return true;
  }
  
  logger.warn('Socket.IO尚未初始化，无法发送消息');
  return false;
};

// 设置用户的socket角色
const setUserRole = (socketId, role) => {
  if (io) {
    const socket = io.sockets.sockets.get(socketId);
    if (socket) {
      socket.join(`role:${role}`);
      logger.debug(`用户Socket ${socketId} 加入角色组 ${role}`);
      return true;
    }
  }
  
  return false;
};

// 获取当前连接数
const getConnectionCount = () => {
  if (io) {
    return io.sockets.sockets.size;
  }
  return 0;
};

// 优雅关闭
const close = () => {
  if (io) {
    io.close();
    logger.info('Socket.IO服务已关闭');
  }
};

module.exports = {
  setup,
  emitToUser,
  emitToAll,
  emitToRoom,
  emitToAdmins,
  setUserRole,
  getConnectionCount,
  close
}; 